/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exchangerate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 *
 * @author Hui
 */
public class ReadFormfile {

    private String fileName = "Currency.txt";

    public ArrayList<Currency> readFromFile() {
        FileReader reader = null;
        ArrayList<Currency> result = new ArrayList<Currency>();

        int count = 0;
        try {
            reader = new FileReader(new File(fileName));
            BufferedReader br = new BufferedReader(reader);
            //read a line
            String row = br.readLine();
            //temp for save all of one account info
            String temp = "";
            StringBuilder read = new StringBuilder();
            while (row != null) {
                temp = read.append(row).toString();
                //read a new line
                row = br.readLine();
            }
            //spilt all the account one by one
            StringTokenizer st = new StringTokenizer(temp, ";");
            while (st.hasMoreTokens() != false) {
                String account = st.nextToken();
                StringTokenizer accountResult = new StringTokenizer(account, ",");
                String name = "";
                double rate = 0.0;
                for (int i = 0; i < 2; i++) {
                    String info = accountResult.nextToken();

                    //get every row info and identify the info of the row
                    switch (i) {
                        case 0:
                            //get the fist row info and set one account Id with this info
                            name = info;
                            break;
                        case 1:
                            //get the second row info and set one account name with this info
                            rate = Double.parseDouble(info);
                            break;
                    }
                }
                result.add(count, new Currency(rate, name));
                count++;
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Error reading from file");
            ex.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                System.out.println("Ignore");
            }
            return result;
        }
    }
}
